package com.ruoyi.framework.web.service;

import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.HttpUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.domain.IdCard;
import com.ruoyi.pay.domain.PayCoinUserForm;
import com.ruoyi.pay.service.IPayCoinUserService;
import com.ruoyi.system.service.ISysUserService;

@Component
public class IdCardService {
	
	@Autowired
	private ISysUserService sysUserService;
	
	@Autowired
	private IPayCoinUserService payCoinUserService;

	/**
	 * 获取身份证正面
	 * @param imageUrl
	 * @return
	 */
	public IdCard getIdCardFront(String imageUrl) {
		IdCard idCard = null;
	    String host = "https://dfidcard.market.alicloudapi.com";
	    String path = "/ocr/idcard";
	    String method = "POST";
	    String appcode = "5f305b6a0eb8473a82df9387c0b78950";
	    Map<String, String> headers = new HashMap<String, String>();
	    //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
	    headers.put("Authorization", "APPCODE " + appcode);
	    //根据API的要求，定义相对应的Content-Type
	    headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	    Map<String, String> querys = new HashMap<String, String>();
	    Map<String, String> bodys = new HashMap<String, String>();
	    bodys.put("image_url", imageUrl);
	    
	    try {
	    	HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
	    	String body = EntityUtils.toString(response.getEntity());
	    	String status = JSONObject.parseObject(body).getString("status");
	    	if("OK".equals(status)){
	    		idCard = JSONObject.parseObject(body).getObject("result", IdCard.class);
	    	}
	    } catch (Exception e) {
	    	throw new ServiceException("调用OCR接口异常");
	    }
	    return idCard;
	}
	
	public String checkIdCard(SysUser user) {
		String state = "0";
	    String host = "https://dfphone3.market.alicloudapi.com";
	    String path = "/verify_id_name_phone";
	    String method = "POST";
	    String appcode = "5f305b6a0eb8473a82df9387c0b78950";
	    Map<String, String> headers = new HashMap<String, String>();
	    //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
	    headers.put("Authorization", "APPCODE " + appcode);
	    //根据API的要求，定义相对应的Content-Type
	    headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	    Map<String, String> querys = new HashMap<String, String>();
	    Map<String, String> bodys = new HashMap<String, String>();
	    bodys.put("id_number", user.getIdNumber());
	    bodys.put("name", user.getIdName());
	    bodys.put("phone_number", user.getPhonenumber());

	    try {
	    	HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
	    	String body = EntityUtils.toString(response.getEntity());
	    	String status = JSONObject.parseObject(body).getString("status");
	    	
	    	PayCoinUserForm payCoinUserForm = new PayCoinUserForm();
    		payCoinUserForm.setUserId(user.getUserId());
    		payCoinUserForm.setCoinNum(100);
    		payCoinUserForm.setCoinType("1");
    		payCoinUserForm.setRemark("实名认证消费");
    		payCoinUserService.savePayCoinUser(payCoinUserForm);
    		
	    	if("OK".equals(status)){
	    		state = JSONObject.parseObject(body).getString("state");
	    		if(!"1".equals(state)){
	    			throw new ServiceException("手机号和身份证不一致");
	    		}
	    	}else{
	    		throw new ServiceException("手机号不正确");
	    	}
	    } catch (Exception e) {
	    	throw new ServiceException(e.getMessage());
	    }
	    return state;
	}

	public void idCard(Long userId) {
		SysUser sysUser = sysUserService.getById(userId);
		if("1".equals(sysUser.getIdCardStatus())){
			return;
		}
		if(StringUtils.isBlank(sysUser.getIdCardFront())){
			throw new ServiceException("请上传身份证正面");
		}
		if(StringUtils.isBlank(sysUser.getIdCardBack())){
			throw new ServiceException("请上传身份证反面");
		}
		if(StringUtils.isBlank(sysUser.getPhonenumber())){
			throw new ServiceException("手机号不能为空");
		}
		
		Integer amount = payCoinUserService.getAmount();
		if(amount < 100){
			throw new ServiceException("认证需要支付1元认证费", 555);
		}
		
		IdCard idCard = getIdCardFront(sysUser.getIdCardFront());
		if(idCard == null){
			throw new ServiceException("请上传清晰的身份证正面");
		}
		// 更新身份证信息
		sysUser.setIdName(idCard.getName());
		sysUser.setBirthday(idCard.getBirthday());
		sysUser.setAge(idCard.getAge());
		sysUser.setIdNumber(idCard.getNumber());
		sysUser.setSex(idCard.getSex());
		sysUserService.updateById(sysUser);
		
		idCard = getIdCardFront(sysUser.getIdCardBack());
		if(idCard == null){
			throw new ServiceException("请上传清晰的身份证反面");
		}
		sysUser.setIdDateLimit(idCard.getTimelimit());
		sysUserService.updateById(sysUser);
		
		String state = checkIdCard(sysUser);
		sysUser.setIdCardStatus(state);
		sysUserService.updateById(sysUser);
		
	}

	public void idCardPhone(String phone) {
		SysUser sysUser = sysUserService.getById(SecurityUtils.getUserId());
		if("1".equals(sysUser.getIdCardStatus())){
			return;
		}
		if(StringUtils.isBlank(phone)){
			throw new ServiceException("手机号不能为空");
		}
		if(StringUtils.isBlank(sysUser.getIdCardFront())){
			throw new ServiceException("请上传身份证正面");
		}
		if(StringUtils.isBlank(sysUser.getIdCardBack())){
			throw new ServiceException("请上传身份证反面");
		}
		IdCard idCard = getIdCardFront(sysUser.getIdCardFront());
		if(idCard == null){
			throw new ServiceException("请上传清晰的身份证正面");
		}
		// 更新身份证信息
		sysUser.setIdPhone(phone);
		sysUser.setIdName(idCard.getName());
		sysUser.setBirthday(idCard.getBirthday());
		sysUser.setAge(idCard.getAge());
		sysUser.setIdNumber(idCard.getNumber());
		sysUser.setSex(idCard.getSex());
		sysUserService.updateById(sysUser);
		
		idCard = getIdCardFront(sysUser.getIdCardBack());
		if(idCard == null){
			throw new ServiceException("请上传清晰的身份证反面");
		}
		sysUser.setIdDateLimit(idCard.getTimelimit());
		String state = checkIdCardPhone(sysUser);
		sysUser.setIdCardStatus(state);
		sysUserService.updateById(sysUser);
	}

	private String checkIdCardPhone(SysUser user) {
		String state = "0";
	    String host = "https://dfphone3.market.alicloudapi.com";
	    String path = "/verify_id_name_phone";
	    String method = "POST";
	    String appcode = "5f305b6a0eb8473a82df9387c0b78950";
	    Map<String, String> headers = new HashMap<String, String>();
	    //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
	    headers.put("Authorization", "APPCODE " + appcode);
	    //根据API的要求，定义相对应的Content-Type
	    headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	    Map<String, String> querys = new HashMap<String, String>();
	    Map<String, String> bodys = new HashMap<String, String>();
	    bodys.put("id_number", user.getIdNumber());
	    bodys.put("name", user.getIdName());
	    bodys.put("phone_number", user.getIdPhone());

	    try {
	    	HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
	    	String body = EntityUtils.toString(response.getEntity());
	    	String status = JSONObject.parseObject(body).getString("status");
    		
	    	if("OK".equals(status)){
	    		state = JSONObject.parseObject(body).getString("state");
	    		if(!"1".equals(state)){
	    			throw new ServiceException("手机号和身份证不一致");
	    		}
	    	}else{
	    		throw new ServiceException("手机号不正确");
	    	}
	    } catch (Exception e) {
	    	throw new ServiceException(e.getMessage());
	    }
	    return state;
	}
}
